<template>
  <div class="app-container">
    <!-- <div class="top-box"> -->
    <el-select v-model="queryParams.vesselName" filterable clearable placeholder="choose Vessel" @change="selectVessel">
      <el-option :key="item.vesselName" :label="item.vesselName" :value="item.vesselName" v-for="item in vessels">
      </el-option>
    </el-select>
    &nbsp;&nbsp;
    <el-select v-model="queryParams.voyageNo" filterable clearable placeholder="Voyage" @change="selectVoyage">
      <el-option :key="item.voyageNo" :label="item.voyageNo" :value="item.voyageNo" v-for="item in voyages">
      </el-option>
    </el-select>
    &nbsp;&nbsp;
    <el-select v-model="queryParams.pol" filterable clearable placeholder="POL">
      <el-option :key="item.portName" :label="item.portName" :value="item.portName" v-for="item in pols">
      </el-option>
    </el-select>
    &nbsp;&nbsp;
    <el-select v-model="queryParams.pod" filterable clearable placeholder="POD">
      <el-option :key="item.portName" :label="item.portName" :value="item.portName" v-for="item in pods">
      </el-option>
    </el-select>
    &nbsp;&nbsp;
    <el-button type="primary" icon="search" @click="search">Search</el-button>
    &nbsp;&nbsp;
    <el-button type="primary" @click="handlePrint">Export</el-button>
    &nbsp;&nbsp;

    <!-- </div> -->
    <el-empty v-if="listData.length === 0" description="No Data" :image-size="100" />
    <h3 style="text-align: center" v-if="listData.length > 0"><strong>CARGO MANIFEST</strong></h3>
    <div v-for="(item, index) in listData" :key="index" class="item-box">
      <!-- <div class="tip-box">
        <div class="tip-item">
          <div class="title"><strong>MV:</strong></div>
          {{ item.vesselName }}
        </div>
        <div class="tip-item">
          <div class="title"> <strong>MV:</strong> </div>
          {{ item.voyageNo }}
        </div>
        <div class="tip-item">
          <div class="title"> <strong>IMO:</strong></div>
          {{ item.imoNumber }}
        </div>
        <div class="tip-item">
          <div class="title"><strong>FROM:</strong></div>
          {{ item.pol }}
        </div>
        <div class="tip-item">
          <div class="title"><strong>ITO:</strong></div>
          {{ item.pod }}
        </div>
        <div class="tip-item">
          <div class="title"><strong>N.R.T.:</strong></div>
          {{ item.nrt }}
        </div>
      </div> -->
      <el-row class="manifest-tip-item__wrapper">
        <el-col :span="6" class="manifest-tip-item">
          <span class="title"><strong>VESSEL NAME</strong></span>{{ item.vesselName }}
        </el-col>
        <el-col :span="6" class="manifest-tip-item">
          <span class="title"><strong>VOYAGE</strong></span>{{ item.voyageNo }}
        </el-col>
        <el-col :span="6" class="manifest-tip-item">
          <span class="title"><strong>FLAG</strong></span>{{ item.flagState }}
        </el-col>
        <el-col :span="6" class="manifest-tip-item">
          <span class="title"><strong>IMO No.</strong></span>{{ item.imoNumber }}
        </el-col>
      </el-row>
      <el-row class="manifest-tip-item__wrapper">
        <el-col :span="6" class="manifest-tip-item">
          <span class="title"><strong>PORT OF LOADING</strong></span>{{ item.pol }}
        </el-col>
        <el-col :span="6" class="manifest-tip-item">
          <span class="title"><strong>PORT OF DISCHARGING</strong></span>{{ item.pod }}
        </el-col>
        <el-col :span="6" class="manifest-tip-item">
          <span class="title"><strong>DATE OF DEPARTURE</strong></span>{{ item.atd }}
        </el-col>
        <el-col :span="6" class="manifest-tip-item">
          <span class="title"><strong>N.R.T.</strong></span>{{ item.nrt }}
        </el-col>
      </el-row>
      <!-- <el-row class="manifest-tip-item__wrapper">
        <el-col :span="8" class="manifest-tip-item" style="padding-top: 0;">
          <el-button type="primary" @click="onMerge({ item, index })">Combine</el-button>
        </el-col>
      </el-row> -->

      <el-table ref="tableRef" stripe :data="item.details" style="width: 100%" :border="true"
        @sort-change="handleSortChange">
        <el-table-column prop="blNo" label="B/L NO." width="160" />
        <el-table-column prop="marks" label="MARKS & NOS." width="200" />
        <el-table-column prop="goodsDesc" label="DESCRIPTION OF GOODS" width="200" />
        <el-table-column label="NO.& KIND OF PKGS" width="240">
          <el-table-column prop="totalUnits" label="G/W" width="120" />
          <el-table-column prop="unit" label="Unit" width="120" />
        </el-table-column>
        <el-table-column prop="totalWeight" label="G/W(KGS)" width="160" header-align="center">
        </el-table-column>
        <el-table-column prop="totalVolume" label="MEASUREMENT(M³)" width="160" />
        <el-table-column prop="shipper" label="SHIPPER" width="200" />
        <el-table-column prop="consignee" label="CONSIGNEE" width="200" />
        <el-table-column prop="notifyParty" label="NOTIFY PARTY" width="300" />
        <el-table-column prop="remark" label="REMARKS" width="120" />
        <el-table-column prop="createBy" label="Created By" width="120" />
        <el-table-column label="Operation" width="90" fixed="right">
          <template #default="scope">
            <span class="btn-primary" v-if="hasAuth(auth, 'edit')" @click="editClickEvent(scope.row)">{{
              $t("ship.button.edit") }}</span>&nbsp;&nbsp;
            <span class="btn-primary"
              v-if="hasAuth(auth, 'edit') && scope.row.goodsDesc != null && scope.row.remark != null"
              @click="handleClose(scope.row.id)">close</span>
          </template>
        </el-table-column>
      </el-table>
    </div>


    <el-dialog class="edit_dialog" destroy-on-close draggable :title="dialogTitle" v-model="dialogFormVisible">
      <el-form :model="formParam" :rules="rules" ref="custForm">
        <el-row>
          <el-col :span="24">
            <el-form-item label="MARKS & NOS." label-width="220px" prop="marks" required>
              <el-input type="textarea" v-model="formParam.marks"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="DESCRIPTION OF GOODS" label-width="220px" prop="goodsDesc" required>
              <el-input type="textarea" v-model="formParam.goodsDesc"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="NO.& KIND OF PKGS" label-width="220px" prop="goodsDesc" required>
              <el-input-number v-model="formParam.totalUnits" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Unit" label-width="220px" prop="unit" required>
              <el-select v-model="formParam.unit">
                <el-option v-for="item in units" :key="item" :value="item" :index="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="REMARKS" label-width="220px" prop="remark">
              <el-input type="textarea" v-model="formParam.remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">{{ $t("ship.button.cancel") }}</el-button>
          <el-button @click="resetForm" type="warning">{{ $t("ship.button.reset") }}</el-button>
          <el-button type="primary" @click="submitForm">{{ $t("ship.button.submit") }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import { ElNotification, ElMessageBox } from "element-plus";
import { downloadFile } from "@/utils/downloadFile";
import service from "@/utils/request";
import { hasAuth } from "@/utils/auth";
import { useMixinAuth } from "@/components/mixin/auth.js";
import { useTableDrag } from '@/hooks/useHooks'
const auth = useMixinAuth();
const { tableRef } = useTableDrag();
let ports = ref([])
let vessels = ref([] as any);
onMounted(async () => {
  getVoyageList();
  refreshTable();
  let result = await service.get("/shipping/port/list");
  if (result) {
    ports.value = result.data;
  }
  result = await service.get("/shipping/schedule/getAllSchedule");
  if (result) {
    vessels.value = result.data;
  }
});

const rules = ref({
  unit: [{ required: true, message: "Unit can't be blank" }]
});

const handlePrint = () => {

}
let voyages = ref([] as any);
let pols = ref([] as any);
let pods = ref([] as any);
// 请求搜索下来条件
const getVoyageList = async () => {
  const { data } = await service.get("/shipping/voyage/list", {
    params: { status: 0 }
  });
  if (data) {
    voyages.value = data;
  }
};

const total = ref(0);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  vesselName: null,
  voyageNo: null,
  pol: null,
  pod: null,
  status: 0,
  orderByColumn: undefined,
  isAsc: undefined
});

const listData = ref([]);

// 搜索列表
const refreshTable = async () => {
  let result = await service.get("/shipping/manifest/export/getTable", {
    params: queryParams,
  });
  listData.value = result.data;
  total.value = result.total
};

const custForm = ref(null);
const dialogTitle = ref("");
const initForm = {
  id: null,
  totalWeight: null,
  status: 0,
  unit: null,
  totalUnits: null,
  totalVolume: null,
  shipper: null,
  consignee: null,
  marks: null,
  goodsDesc: null,
  remark: null
}

const units = ["BOXES", "CARTONS", "UNITS", "SKIDS", "PALLETS"]

const formParam = reactive(Object.assign({}, initForm));
const dialogFormVisible = ref(false);

const editClickEvent = (row: any) => {
  dialogTitle.value = "Update manifest";
  dialogFormVisible.value = true;
  Object.keys(initForm).forEach(k => (formParam[k] = row[k]));
  isAdd = false;
};

const handleClose = async (id) => {
  ElMessageBox.confirm("CONFIRM CLOSED？", "Confirmation Information", {
    type: "warning",
    confirmButtonText: "Confirm",
    cancelButtonText: "Cancel",
  }).then(async () => {
    await service.put(`shipping/manifest/export/close/${id}`)
    ElNotification.success({
      title: "Prompt information",
      message: "close manifest success!",
      position: "bottom-right"
    });
    refreshTable()
  })
}
let isAdd = false;

const pageQuery = async e => {
  queryParams.pageNum = e.page;
  queryParams.pageSize = e.limit;
  refreshTable();
};

const search = () => {
  refreshTable();
};

function handleExport() {
  downloadFile("/shipping/manifest/export", queryParams, `${new Date().getTime()}MANIFEST.xlsx`);
}

const selectVessel = async () => {
  //@ts-ignore
  let item = vessels.value.find(n => n.vesselName == queryParams.vesselName)
  voyages.value = item.schedules
}

const selectVoyage = async () => {
  //@ts-ignore
  let item = voyages.value.find(n => n.voyageNo == queryParams.voyageNo)
  pods.value = item.pods
  pols.value = item.pols
}

const handleSortChange = async (column: any) => {
  queryParams.orderByColumn = column.prop;
  queryParams.isAsc = column.order; //动态取值排序顺序
  refreshTable();
};

const resetForm = () => {
  // @ts-ignore
  custForm.value.resetFields();
};

const submitForm = () => {
  custForm.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
    await service["put"]("shipping/manifest", formParam);
    // @ts-ignore
    ElNotification.success({
      title: "Prompt information",
      message: "save successful!",
      position: "bottom-right"
    });
    dialogFormVisible.value = false;
    refreshTable()
  });
}  
</script>
<style lang="scss" scoped>
.manifest-tip-item__wrapper {
  padding-left: 16px;

  &:first-child {
    padding-top: 16px;
  }

  .manifest-tip-item {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    padding: 0 2px 16px 0;
    font-size: 13px;

    .title {
      display: inline-block;
      width: 170px;
    }
  }
}
</style>